<template>
  <div class="content">
    <div class="mapInfo">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>创建思维导图</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="info" v-if="$route.query.mapId">
        <h4>
          <span>{{ mapInfo.title }}</span>
        </h4>
        <span>备注：{{ mapInfo.remark }}</span>
      </div>
      <div class="mapOSBtn" >
        <el-button v-if="isUserInfo('vip')" type="primary" @click="changeLineStyle" size="medium" round
          >切换连线样式</el-button
        >
        <el-button v-if="isUserInfo('vip')" type="primary" @click="changeTheme" size="medium" round
          >切换主题</el-button
        >
        <el-button v-if="isUserInfo('vip')" type="primary" @click="changeLayout" size="medium" round
          >切换结构</el-button
        >
        <el-button v-if="$route.query.mapId" type="primary" @click="exportFile" size="medium" round
          >导出</el-button
        >
      </div>
    </div>
    <el-divider></el-divider>
    <div id="mindMapContainer"></div>

    <div class="toolbar" v-if="$route.query.type !== 'read'">
      <button @click="back" v-if="!isStart">回退</button>

      <button @click="forward" v-if="!isEnd">前进</button>

      <button @click="insertNode" v-if="activeNodes.length > 0">
        插入兄弟节点
      </button>

      <button @click="insertChildNode" v-if="activeNodes.length > 0">
        插入子节点
      </button>

      <button @click="deleteNode" v-if="activeNodes.length > 0">
        删除节点
      </button>
      <button @click="changeNodeShape" v-if="activeNodes.length > 0&&isUserInfo('vip')">
        切换节点形状
      </button>
      <button @click="changeNodeBg" v-if="activeNodes.length > 0&&isUserInfo('vip')">
        切换节点背景
      </button>
      <button @click="changeNodeColor" v-if="activeNodes.length > 0&&isUserInfo('vip')">
        切换字体颜色
      </button>
    </div>

    <!-- <BiVueMindmap ref="bi-vue-mindmap" class="mindMap" :allowDrop='false' :flatNodes="mindmapNodes" /> -->

    <div
      class="adMain"
      v-if="$route.query.type == 'add' || $route.query.type == 'edit'"
    >
      <el-button type="primary" plain @click="onDialog()"
        >{{ $route.query.type == "add" ? "创建" : "保存" }}思维导图</el-button
      >
    </div>
    <el-dialog
      title="保存文件"
      :visible.sync="dialogVisible"
      width="30%"
      center
      :before-close="handleClose"
    >
      <div class="diaCont">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="思维导图名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="onCreat()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MindMap from "simple-mind-map";
import Export from 'simple-mind-map/src/plugins/Export.js'


export default {
  name: "map",
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem("user")) || null,
      dialogVisible: false,
      activeNodes: [],
      isStart: true,
      isEnd: true,
      mapInfo: {},
      mapSetData:{},
      mapData: {
        data: {
          text: "根节点",
        },
        children: [
          {
            data: {
              text: "二级节点",
            },
            children: [],
          },
          {
            data: {
              text: "二级节点",
            },
            children: [],
          },
        ],
      },
      ruleForm: {},
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {},
  mounted() {
    // 首次初始化
    if (this.$route.query.mapId) {
      this.getInfo();
    } else {
      this.onMapInit();
    }
  },
  methods: {
    isUserInfo(role){
      if(role&&role=="admin"&&this.userInfo&&this.userInfo.role==1){
        return true
      } 
      if(role&&role=="vip"&&this.userInfo&&this.userInfo.role==2){
        return true
      } 
      if(this.userInfo&&this.userInfo.userId&&!role){
        return true
      } else return false
    },
    onDialog() {
      this.dialogVisible = !this.dialogVisible;
      if (this.$route.query.type !== "add") {
        this.ruleForm.name = this.$route.query.title;
        this.ruleForm.remark = this.$route.query.remark;
      }
    },
    // 回退
    back() {
      this.mindMap.execCommand("BACK");
    },

    // 前进
    forward() {
      this.mindMap.execCommand("FORWARD");
    },

    // 插入兄弟节点
    insertNode() {
      this.mindMap.execCommand("INSERT_NODE");
    },

    // 插入子节点
    insertChildNode() {
      this.mindMap.execCommand("INSERT_CHILD_NODE");
    },

    // 删除节点
    deleteNode() {
      this.mindMap.execCommand("REMOVE_NODE");
    },
    // 切换结构
    changeLayout() {
      let Layout = this.mindMap.getLayout();
      console.log(this.mindMap, "mindMap", Layout);
      let styles = ["mindMap", "organizationStructure", "catalogOrganization", "logicalStructure"];
      let index = styles.indexOf(Layout);
      if (index != -1) {
        if (index == styles.length - 1) {
          this.mindMap.setLayout(styles[0]);
        } else {
          this.mindMap.setLayout(styles[++index]);
        }
      }
    },
    // 切换主题
    changeTheme() {
      let theme = this.mindMap.getTheme();
      console.log(this.mindMap, "mindMap", theme);
      let styles = ["default", "classic", "minions", "dark"];
      let index = styles.indexOf(theme);
      if (index != -1) {
        if (index == styles.length - 1) {
          this.mindMap.setTheme(styles[0]);
        } else {
          this.mindMap.setTheme(styles[++index]);
        }
      }
    },
    // 切换连线样式
    changeLineStyle() {
      console.log(this.mindMap, "mindMap");
      let styles = ["curve", "straight", "direct"];
      let lineStyle = this.mindMap.themeConfig.lineStyle;
      let index = styles.indexOf(this.mindMap.themeConfig.lineStyle);
      if (index != -1) {
        if (index == styles.length - 1) {
          lineStyle = styles[0];
        } else {
          lineStyle = styles[++index];
        }
      }
      this.mindMap.setThemeConfig({
        // lineColor: '#009CE0',
        // lineWidth: 2,
        // lineDasharray: '15, 10, 5, 10, 15',
        lineStyle: lineStyle,
      });
    },
    // 切换节点形状
    changeNodeShape() {
      console.log(this.mindMap, "mindMap");
      let styles = [
        {
          name: "矩形",
          value: "rectangle",
        },
        {
          name: "菱形",
          value: "diamond",
        },
        {
          name: "平行四边形",
          value: "parallelogram",
        },
        {
          name: "圆角矩形",
          value: "roundedRectangle",
        },
        {
          name: "八角矩形",
          value: "octagonalRectangle",
        },
        {
          name: "外三角矩形",
          value: "outerTriangularRectangle",
        },
        {
          name: "内三角矩形",
          value: "innerTriangularRectangle",
        },
        {
          name: "椭圆",
          value: "ellipse",
        },
        {
          name: "圆",
          value: "circle",
        },
      ];
      this.activeNodes.forEach(node => {
        let shapeInfo = node.getStyle()
        console.log(node,'node');
        console.log(shapeInfo,'shapeInfo');
        let num = styles.length-1
        for (let i = styles.length-1; i > 0; i--) {
          const item = styles[i];
          if (item.value==shapeInfo.shape) {
            num = i-1
            break
          }
        }
        node.setStyle('shape', styles[num].value)
      })
      console.log(this.activeNodes,'this.activeNodes');
    },
    // 切换节点字体颜色
    changeNodeColor() {
      console.log(this.mindMap, "mindMap");
      let styles = [undefined,'#fff','red','blue','pink','black'];
      this.activeNodes.forEach(node => {
        let shapeInfo = node.getStyle()
        console.log(node,'node');
        console.log(shapeInfo,'shapeInfo');
        let num = styles.length-1
        for (let i = styles.length-1; i > 0; i--) {
          const item = styles[i];
          if (item==shapeInfo.color) {
            num = i-1
            break
          }
        }
        node.setStyle('color', styles[num])
      })
      console.log(this.activeNodes,'this.activeNodes');
    },
    // 切换节点背景
    changeNodeBg() {
      console.log(this.mindMap, "mindMap");
      let styles = [undefined,'#fff','red','blue','pink','black'];
      this.activeNodes.forEach(node => {
        let shapeInfo = node.getStyle()
        console.log(node,'node');
        console.log(shapeInfo,'shapeInfo');
        let num = styles.length-1
        for (let i = styles.length-1; i > 0; i--) {
          const item = styles[i];
          if (item==shapeInfo.fillColor) {
            num = i-1
            break
          }
        }
        node.setStyle('fillColor', styles[num])
      })
    },
    // 导出数据
    exportFile() {
      this.mindMap.export('json', true, this.mapInfo.title)
      // this.mindMap.export('md', true, this.mapInfo.title)
    },
    handleClose() {
      this.dialogVisible = !this.dialogVisible;
      this.ruleForm = {};
    },
    // 导图初始化
    onMapInit() {
      MindMap.usePlugin(Export)
      console.log(this.mapSetData,'this.mapSetData');
      let  { root, layout, theme, view } = this.mapSetData
      let obj = {}
      if (root) {
        obj.root = root
      } else {
        root=this.mapData
      }
      if (layout) {
        obj.layout = layout
      }
      if (theme) {
        obj.theme = theme.template
        obj.themeConfig = theme.config
      }
      if (view) {
        obj.viewData = view
      }
      this.mindMap = new MindMap({
        el: document.getElementById("mindMapContainer"),
        data: root,
        initRootNodePosition: ["left", "center"],
        enableFreeDrag: true,
        ...obj
      });
      // 监听节点激活事件
      this.mindMap.on("node_active", (node, nodeList) => {
        console.log(node, "node");
        this.activeNodes = nodeList;
      });

      // 前进回退事件
      this.mindMap.on("back_forward", (index, len) => {
        this.isStart = index <= 0;
        this.isEnd = index >= len - 1;
      });
    },
    getRoot(root) {
      if (root.children.length == 0) {
        return {
          data: { text: root.data.text },
          children: [],
        };
      } else {
        return {
          data: { text: root.data.text },
          children: root.children.map((item) => {
            return this.getRoot(item);
          }),
        };
      }
    },
    // 获取导图信息
    getInfo() {
      this.$api.getMapInfoById({ id: this.$route.query.mapId }).then((res) => {
        console.log(res);
        if (res.code === 200) {
          this.mapInfo = res.data;
          // this.mapData = res.data.mapData
          const mapData = JSON.parse(res.data.mapData);
          let  { root, layout, theme, view } = mapData
          this.mapData = this.getRoot(root);
          this.mapSetData = mapData
          this.$set(this, "mapData", this.getRoot(root));
          console.log(this.mapData);
          this.onMapInit();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    onCreat() {
      console.log(this.mindMap.getData(true));
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let obj = {
            mapId: this.$route.query.mapId || "",
            userId: this.userInfo.userId,
            title: this.ruleForm.name,
            remark: this.ruleForm.remark,
            mapData: JSON.stringify(this.mindMap.getData(true)),
          };
          this.$api.postAddMap(obj).then((res) => {
            console.log(res);
            if (res.code === 200) {
              this.$message.success("创建成功");
              this.$router.push({
                name: "mapList",
              });
            } else {
              this.$message.error(res.info);
            }
          });
        } else {
          return false;
        }
      });
    },
    onCreat2() {
      console.log(this.mindMap.getData(true));
      // this.mindMap.getData(true);
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let mapList = JSON.parse(sessionStorage.getItem("mapList")) || [];
          let obj = {
            id: 1 + mapList.length,
            title: this.ruleForm.name,
            data: this.mindMap.getData(true),
          };
          if (sessionStorage.getItem("mapList")) {
            for (let idx = 0; idx < mapList.length; idx++) {
              const item = mapList[idx];
              if (item.userId === this.userInfo.userId) {
                item.list.push(obj);
                console.log(item.list, "item.list");
                sessionStorage.setItem("mapList", JSON.stringify(mapList));
                break;
              } else if (idx === mapList.length - 1) {
                // 新用户导图
                mapList.push({
                  userId: this.userInfo.userId,
                  list: [obj],
                });
                sessionStorage.setItem("mapList", JSON.stringify(mapList));
              }
            }
          } else {
            // 新用户导图
            mapList.push({
              userId: this.userInfo.userId,
              list: [obj],
            });
            sessionStorage.setItem("mapList", JSON.stringify(mapList));
          }
          this.$router.push({
            name: "mapList",
          });
        } else {
          return false;
        }
      });
    },
    toLogin() {
      this.$emit("toLogin");
    },
  },
};
</script>

<style lang="scss" scoped>
.adMain {
  margin-top: 20px;
}
.toolbar {
  position: absolute;
  left: 50vh;
  top: 300px;
}

#mindMapContainer {
  width: 100%;
  height: 70vh;
}

#mindMapContainer * {
  margin: 0;
  padding: 0;
}

::v-deep .mindMap .main {
  height: calc(75vh - 32px) !important;
}

::v-deep .mindMap .bottom .left .btn {
  display: none;
}

.el-main {
  // min-height: 85vh;
  // background: #ffffff;
  //     display: flex;
  // justify-content: center;
  // align-items: center;
  .content {
    position: relative;
    min-height: 80vh;
    width: 80%;
    padding: 50px 0;
    margin: 0 auto;
    .mapInfo {
      .info {
        margin-bottom: 20px;
      }
      .mapOSBtn {
      }
    }
  }
  .adMain {
  }
  .el-carousel__item {
    background: #409eff;
  }
}
</style>
